﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using DevComponents.AdvTree;
using DevComponents.DotNetBar;
using PlanningGIS.Win.Controls;
using PlanningGIS.ManageUtility;
using PlanningGIS.Framework;
using PlanningGIS.Util.Log;
using PlanningGIS.ManageUtility.Modules;

namespace PlanningGIS.Manager
{
    /// <summary>
    /// 功能配置树
    /// </summary>
    public partial class FuncTree : AdvTree
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public FuncTree()
        {
            InitializeComponent();            
        }

        /// <summary>
        /// 
        /// </summary>
        private bool _IsChange = false;

        /// <summary>
        /// 
        /// </summary>
        public bool IsChange
        {
            get { return _IsChange; }
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnAfterCheck(AdvTreeCellEventArgs e)
        {
            _IsChange = true;
            base.OnAfterCheck(e);
        }

        /// <summary>
        /// 重置控件
        /// </summary>
        public void ResetControl()
        {
            _IsChange = false;
        }

        /// <summary>
        /// 从Xml读取功能配置
        /// </summary>
        /// <param name="fullname"></param>
        public void ReadFile(string fullname)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(fullname);
                ReadXml(doc.InnerXml);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowInfomationMsgbox("打开文件失败,可能规则文件格式不正确:" + ex.Message);
            }
        }

        /// <summary>
        /// 从xml读取功能权限配置
        /// </summary>
        /// <param name="xml">功能配置</param>
        /// <param name="remove">是否移除不可用的菜单项</param>
        public void ReadXml(string xml, bool remove = false)
        {
            Nodes.Clear();
            PrivilegeGroup funcGroup = new PrivilegeGroup();
            try
            {                
                funcGroup.Xml = xml;
                List<IPrivilegeElement> groups = funcGroup.GetChilds();
                if (groups == null || groups.Count == 0) return ;
                foreach (IPrivilegeGroup group in groups)
                {
                    if (remove && !group.Enable) continue;
                    AddNode(group, null, remove);
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("打开文件失败,可能规则文件格式不正确:" + ex.Message);
            }
            this.Refresh();
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="item"></param>
        /// <param name="parentNode"></param>
        /// <param name="remove">是否移除不可用的菜单项</param>
        private void AddNode(IPrivilegeElement item, Node parentNode, bool remove = false)
        {
            if (remove && !item.Enable) return;
            Node nd = new Node();
            nd.Tag = item;
            nd.Text = item.Text;
            nd.Tooltip = item.TypeName;
            nd.CheckBoxVisible = true;
            nd.Checked = item.Enable;
            if (item is Privilege)
            {
                string tmp = item.NakedText.Replace("/", "");
                try
                {
                    string[] imgs = Directory.GetFiles(AppConfig.ImagePath+"\\32X32", tmp + ".*", SearchOption.AllDirectories);
                    if (imgs != null && imgs.Length > 0)
                        nd.Image = new Bitmap(imgs[0]);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorText(ex);
                }
            }
            else if (item is PrivilegeGroup)
            {
                PrivilegeGroup group = item as PrivilegeGroup;
                //group.TypeName = typeof(Bar).FullName + "," + typeof(Bar).Assembly.GetName().Name;
                group.TypeName = item.TypeName;
                nd.Tag = group;
                List<IPrivilegeElement> groups = group.GetChilds();
                if (groups != null && groups.Count > 0)
                {
                    foreach (IPrivilegeElement child in group.GetChilds())
                    {
                        AddNode(child, nd);
                    }
                }
            }
            if (parentNode == null) this.Nodes.Add(nd);
            else parentNode.Nodes.Add(nd);
        }

        /// <summary>
        /// 增加菜单项
        /// </summary>
        /// <param name="nodes">父节点的子节点集合</param>
        /// <param name="remove">是否移除不可用的菜单项</param>
        /// <returns>增加的节点 </returns>
        public Node AddMenu(NodeCollection nodes, bool remove = false)
        {
            Node treeNode = new Node("新建菜单");
            PrivilegeGroup group = new PrivilegeGroup();
            group.Text = "新建菜单";
            group.TypeName = typeof(Bar).FullName + "," + typeof(Bar).Assembly.GetName().Name;
            group.Enable = true;
            treeNode.Tag = group;
            treeNode.ImageIndex = 0;
            nodes.Add(treeNode);
            return treeNode;
        }

        /// <summary>
        /// 获取功能配置Xml信息
        /// </summary>
        /// <returns></returns>
        public string GetXml()
        {
            PrivilegeGroup p = GetPrivilegeGroup();
            if (p == null) return "";
            return p.Xml;
        }

        /// <summary>
        /// 导出功能权限到文件中
        /// </summary>
        /// <param name="fullname"></param>
        public void ExportXml(string fullname)
        {
            try
            {
                PrivilegeGroup p = GetPrivilegeGroup();
                if (p == null) return;
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(p.Xml);
                xmlDoc.Save(fullname);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }            
        }

        /// <summary>
        /// 导出功能配置到Xml
        /// </summary>
        /// <returns></returns>
        public PrivilegeGroup GetPrivilegeGroup()
        {
            PrivilegeGroup roleContent = new PrivilegeGroup();
            foreach (Node node in Nodes)
            {
                PrivilegeGroup group = node.Tag as PrivilegeGroup;
                group.GetChilds().Clear();
                group.Text = node.Text;
                roleContent.AddChild(group);
                foreach (Node treeNode in node.Nodes)
                {
                    Add2Group(group, treeNode);
                }
            }
            return roleContent;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="group"></param>
        /// <param name="treenode"></param>
        private void Add2Group(PrivilegeGroup group, Node treenode)
        {
            IPrivilegeElement elem = treenode.Tag as IPrivilegeElement;
            elem.Text = treenode.Text;
            group.AddChild(elem);
            if (elem is PrivilegeGroup)
            {
                PrivilegeGroup group1 = elem as PrivilegeGroup;
                group1.GetChilds().Clear();
                foreach (Node node in treenode.Nodes)
                {
                    Add2Group(group1, node);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rels"></param>
        /// <param name="nodes"></param>
        public void SetEnableAll(List<Role_Rel> rels, NodeCollection nodes)
        {
            foreach (Node nd in nodes)
            {
                if (nd.Nodes.Count > 0) SetEnableAll(rels, nd.Nodes);
                if (nd.Tag == null) continue;
                string id = ((IPrivilegeElement)nd.Tag).GetKeyName();
                Role_Rel r = null;
                if (rels!=null)
                    r = rels.FirstOrDefault<Role_Rel>(t => t.RelID.Equals(id, StringComparison.CurrentCultureIgnoreCase));
                nd.Checked = r == null ? false : true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="enable"></param>
        /// <param name="node"></param>
        public void SetEnableAll(bool enable, Node node)
        {
            if (node == null)
            {
                SetEnableAll(enable, this.Nodes);
            }
            else
            {
                node.Checked = enable;
                ((IPrivilegeElement)node.Tag).Enable = enable;
                SetEnableAll(enable, node.Nodes);
            }
        }

        /// <summary>
        /// 启用或禁用所有功能
        /// </summary>
        /// <param name="enable"></param>
        public void SetEnableAll(bool enable, NodeCollection nodes)
        {
            if (nodes == null || nodes.Count == 0) return;
            foreach (Node nd in nodes)
            {
                nd.Checked = enable;
                ((IPrivilegeElement)nd.Tag).Enable = enable;
                SetEnableAll(enable, nd.Nodes);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void ViewMenus()
        {
            try
            {
                IPrivilegeGroup group = this.GetPrivilegeGroup();
                List<IPrivilegeGroup> groups = new List<IPrivilegeGroup>();
                foreach (IPrivilegeElement element in group.GetChilds())
                {
                    if (element is IPrivilegeGroup) groups.Add(element as IPrivilegeGroup);
                }
                FrmView frm = new FrmView();
                frm.View(groups);
                frm.Show();
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
            
        }

    }
}
